//
//  EFANoticeDetailVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/30.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFANoticeDetailVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFANoticeTCell.h"
#import "EFANoticeDetTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFANoticeEditVC.h"
#import "KSPhotoBrowser.h"

@interface EFANoticeDetailVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFANoticeDetTCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *deleteBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *closeBarBtnItem;
//@property (nonatomic, strong) EFADeviceModel *deviceModel;
@end

static NSString *const kReuseCellId = @"EFANoticeTCell";
static NSString *const kReuseDetCellId = @"EFANoticeDetTCell";
//static NSInteger const kRequestSize = 20;

@implementation EFANoticeDetailVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = self.noticeItem ? self.noticeItem.efairyannouncement_title : @"公告详情";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    if (self.presentingViewController) {
        self.navigationItem.leftBarButtonItem = self.closeBarBtnItem;
    }
    if (self.noticeItem.efairyannouncement_publisher_id == [EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) {
        self.navigationItem.rightBarButtonItem = self.deleteBarBtnItem;
    }
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    UINib *detNib = [UINib nibWithNibName:kReuseDetCellId bundle:nil];
    [self.tableView registerNib:detNib forCellReuseIdentifier:kReuseDetCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
//    self.tableView.mj_footer = self.mj_footer;
    
    // 从推送跳转过来的
    if (!self.noticeItem && self.noticeId) {
        [self requestNoticeDetailWithNoticeId:self.noticeId];
    }
    // 列表过来要置为已读
    [self markNoticeAsRead];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有公告" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return self.noticeItem.efairyannouncement_image_list.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        EFANoticeTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        [cell configViewInDetailWithListItem:self.noticeItem];
        return cell;
    }
    
    EFANoticeDetTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseDetCellId forIndexPath:indexPath];
    if (indexPath.row < self.noticeItem.efairyannouncement_image_list.count) {
        [cell configViewWithNotImgItem:self.noticeItem.efairyannouncement_image_list[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 9.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    if (indexPath.row == 0 && indexPath.section < self.pjtDetail.device_list.count) {
    //        EFADeviceListItem *item = self.pjtDetail.device_list[indexPath.section];
    //        [self jumpToDeviceDetailWithDevItem:item];
    //    }
}

#pragma mark - EFANoticeDetTCellDelegate
- (void)noticeDetTCell:(EFANoticeDetTCell *)cell imgViewDownload:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath) {
        [self.tableView reloadData];
    }
}

- (void)noticeDetTCell:(EFANoticeDetTCell *)cell imgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    EFANotImgItem *item = self.noticeItem.efairyannouncement_image_list[indexPath.row];
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:imgView
                                                    imageUrl:[NSURL URLWithString:item.efairyannouncementimage_imgurl]];
    [self showPhotoBrowser:@[photoItem] selectedIndex:0];
}

#pragma mark - event response
- (void)deleteBarBtnTapped:(UIBarButtonItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定删除该公告吗？" message:@"删除公告后，其他人将无法看到该公告" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestDeleteNotice];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)closeBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - private methods
- (void)showPhotoBrowser:(NSArray<KSPhotoItem *> *)photoItems selectedIndex:(NSUInteger)index {
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:photoItems selectedIndex:index];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

- (void)markNoticeAsRead {
    if (self.noticeItem && !self.noticeItem.efairyuserhasannouncement_is_read) {
        [self requestSetNoticeReadWithNoticeId:self.noticeItem.efairyannouncement_id];
    }
}

- (void)backToParent {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:^{
            if (self.successDelHandle) {
                self.successDelHandle();
                self.successDelHandle = nil;
            }
        }];
    } else {
        if (self.successDelHandle) {
            self.successDelHandle();
            self.successDelHandle = nil;
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.pjtDetail.isDeviceTotalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.navigationItem.title = self.noticeItem.efairyannouncement_title;
    if (self.noticeItem.efairyannouncement_publisher_id == [EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) {
        self.navigationItem.rightBarButtonItem = self.deleteBarBtnItem;
    }
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestPjtDeviceListWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestNoticeDetailWithNoticeId:(NSInteger)noticeId {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyannouncement_id" : @(noticeId)};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiAnnouncement] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表返回：%@", responseObject);
        [hud hideAnimated:YES];
        self.noticeItem = [EFANotListItem yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self refreshWholeView];
        // 标记为已读
        [self markNoticeAsRead];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestSetNoticeReadWithNoticeId:(NSInteger)noticeId {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyannouncement_id" : @(noticeId)};
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiAnnouncementIsRead] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求删除设备返回：%@", responseObject);
        self.noticeItem.efairyuserhasannouncement_is_read = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求删除设备失败：%@", error);
    }];
}

- (void)requestDeleteNotice {
    if (!self.noticeItem) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"announcement_id_list" : [@[@(self.noticeItem.efairyannouncement_id)] yy_modelToJSONString]};
    [[XDAFNetworking sharedInstance] DELETE:[ApiManager apiAnnouncement] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"删除公告成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)deleteBarBtnItem {
    if (!_deleteBarBtnItem) {
        _deleteBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"app_not_delete"] style:UIBarButtonItemStylePlain target:self action:@selector(deleteBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_deleteBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _deleteBarBtnItem;
}
- (UIBarButtonItem *)closeBarBtnItem {
    if (!_closeBarBtnItem) {
        _closeBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBarBtnTapped:)];
    }
    return _closeBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}
@end
